<?php
namespace app\home\controller;
use think\Input;
use think\Db;
use clt\Leftnav;
use think\Request;
use think\Controller;
define("TOKEN", "jinpai");//你微信定义的token
define("APPID", "wx828cb7a5bd592f3a");//你微信定义的appid
define("APPSECRET","59211108f4d05016aa0d3226576bac29");//你微信公众号的appsecret
class Wechat extends Controller{
    //第一步：用户同意授权，获取code
    function accept(){
        //这个链接是获取code的链接 链接会带上code参数
        $REDIRECT_URI =url('getCode');
        echo $REDIRECT_URI."<br>";
        $REDIRECT_URI = urlencode($REDIRECT_URI);
        echo $REDIRECT_URI."<br>";
        $scope = "snsapi_userinfo";
        echo $scope."<br>";
        $state = md5(mktime());
        echo $state."<br>";
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".$REDIRECT_URI."&response_type=code&scope=".$scope."&state=".$state."#wechat_redirect";
        header("location:$url");

    }
    //用户同意之后就获取code  通过获取code可以获取一切东西了  机智如我
    function getCode(){
        //获取accse_token
        $code = $_GET["code"];
        //用code获取access_token
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".APPSECRET."&code=".$code."&grant_type=authorization_code";
        //这里可以获取全部的东西  access_token openid scope
        $res = $this->https_request($url);
        $res  = json_decode($res,true);
        $openid = $res["openid"];
        echo "<pre>";
        $access_token = $res["access_token"];
        //echo $access_token;
        //这里是获取用户信息
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->https_request($url);
        $res = json_decode($res,true);
        $data['openid']=$res['openid'];
        $data['unionid']=$res['unionid'];
        $data['head_pic']=$res['headimgurl'];
        $data['city']=$res['unionid'];
        $data['nickname']=$res['nickname'];
        $data['sex']=$res['sex'];
        $tag=Db::table(config('database.prefix').'users')->insert($data);
        if($tag){
            session('weiuserinfo',$data);
        }else{
            $this->error('出错了，请重试');
        }
        header("location:".url('Index/index'));
    }
    function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    public function _empty(){
        return $this->error('空操作，返回上次访问页面中...');
    }
}